﻿#region Copyright
/* © 2008 George Tsiokos, licensed under the Microsoft Reciprocal License (Ms-RL) */
#endregion
using System.Collections.Generic;
using Comet.Collections.Generic;
using System.Threading;

namespace Comet.ComponentModel {
    /// <summary>Experimental</summary>
    internal sealed class BusView<T> : IBusView<T> {

		#region Fields (2) 

        private TemporalIndex _index;
        private readonly PersistedBus<T> _persistedBus;

		#endregion Fields 

		#region Constructors (1) 

        public BusView (PersistedBus<T> persistedBus, long counter) {
            _persistedBus = persistedBus;
        }

		#endregion Constructors 

		#region Properties (2) 

        public T Value {
            get {
                KeyValuePair<TemporalIndex, T> value = _persistedBus.IndexAndValue;
                _index = value.Key;
                return value.Value;
            }
        }

        public IEnumerable<T> Values {
            get {
                MutableValueWrapper<TemporalIndex> index = new MutableValueWrapper<TemporalIndex> (_index);
                //note: must iterate to receive new counter value
                foreach (T item in _persistedBus.GetFrom (index))
                    yield return item;
                _index = index.Value;
            }
        }

		#endregion Properties 

		#region Methods (2) 


		// Public Methods (2) 

        public void Publish (T value) {
            _persistedBus.Publish (value);
        }

        public WaitHandle Subscribe () {
            return _persistedBus.Subscribe ();
        }


		#endregion Methods 

    }
}